package com.lxb.myforum.mail

import java.io.File

import javax.mail.MessagingException

import com.lxb.myforum.base.BaseService
import org.springframework.beans.factory.annotation.Autowired
import org.springframework.beans.factory.annotation.Value
import org.springframework.mail.SimpleMailMessage
import org.springframework.mail.javamail.JavaMailSender
import org.springframework.mail.javamail.MimeMessageHelper
import org.springframework.stereotype.Component

@Component
class MailService @Autowired
constructor(private val mailSender: JavaMailSender) : BaseService() {

    @Value("\${mail.from}")
    private var from: String? = null

    fun sendSimpleMail(to: String, subject: String, content: String) {
        val message = SimpleMailMessage()
        message.setFrom(from!!)
        message.setTo(to)
        message.setSubject(subject)
        message.setText(content)

        try {
            mailSender.send(message)
            logger.info("简单邮件已经发送。")
        } catch (e: Exception) {
            logger.error("发送简单邮件时发生异常！", e)
        }

    }

    fun sendHtmlMail(to: String, subject: String, content: String) {
        val message = mailSender.createMimeMessage()
        try {
            //true表示需要创建一个multipart message
            val helper = MimeMessageHelper(message, true)
            helper.setFrom(from!!)
            helper.setTo(to)
            helper.setSubject(subject)
            helper.setText(content, true)
            //	        helper.

            mailSender.send(message)
            logger.info("html邮件发送成功")
        } catch (e: MessagingException) {
            logger.error("发送html邮件时发生异常！", e)
        }

    }

    fun sendAttachmentMail(to: String, subject: String, content: String) {
        val message = mailSender.createMimeMessage()
        try {
            //true表示需要创建一个multipart message
            val helper = MimeMessageHelper(message, true)
            helper.setFrom(from!!)
            helper.setTo(to)
            helper.setSubject(subject)
            helper.setText(content, true)
            val file = File("/Users/lion/Desktop/20160915110718912.png")
            helper.addAttachment("Test File", file)

            mailSender.send(message)
            logger.info("html邮件发送成功")
        } catch (e: MessagingException) {
            logger.error("发送html邮件时发生异常！", e)
        }
    }
}
